package com.example.demo.controller;

import com.example.demo.pojo.Customer;
import com.example.demo.pojo.Result;
import com.example.demo.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class CustomerController {

    @Autowired
    CustomerService customerService;

    @GetMapping("/cust")
    public List<Customer> selectAllCustomers(){
        return customerService.selectAllCustomers();
    }

    @PostMapping("/cust/search")
    public Customer selectCustomerByid(@RequestBody Customer customer){
        int customer_id = customer.getCustomer_id();
        Customer customer1= customerService.selectCustomerByid(customer_id);
        if (customer1 != null){
            return customer1;
        }
        return null;
    }

    @PostMapping("cust/add")
    public Result addCustomer(@RequestBody Customer customer){
        if(customer == null){
            return Result.error("空对象");
        }else{
            customerService.addCustomer(customer);
            return Result.success();
        }
    }

    @PutMapping("cust/update/{id}")
    public Result updateCustomer(@PathVariable int id, @RequestBody Customer customer){
        if(id>200000){
            customer.setCustomer_id(id);
            customerService.updateCustomer(customer);
            return Result.success();
        }else{
            return Result.error("更新失败");
        }
    }

    @DeleteMapping("cust/delete/{id}")
    public Result deleteCustomer(@PathVariable int id){
        if(id>=200000){
            customerService.deleteCustomer(id);
            return Result.success();
        }else{
            return Result.error("删除失败");
        }
    }

    @PostMapping("/cust/import")
    public Result importCustomer(@RequestBody List<Customer> customerlist){
        if(customerlist != null){
            customerService.changeAll(customerlist);
            return Result.success();
        }else{
            return Result.error("导入失败");
        }
    }

    @GetMapping("/cust/cust_num")
    public Result cust_num() {
        int num = customerService.cust_num();
        if (num != 0){
            customerService.cust_num();
            return Result.success(num);
        }
        return Result.error("获取总客户数失败");
    }

}
